package ldh.im.fxbase.component;

import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;

import java.util.concurrent.Callable;

public class ResizingTextArea extends TextArea {

    public ResizingTextArea() {
        this.setWrapText(true);

        this.sceneProperty().addListener(new ChangeListener<Scene>() {
            @Override
            public void changed(ObservableValue<? extends Scene> obs, Scene oldScene, Scene newScene) {
                if (newScene != null) {
                    ResizingTextArea.this.applyCss();
                    Node text = ResizingTextArea.this.lookup(".text");
                    ResizingTextArea.this.prefHeightProperty().bind(Bindings.createDoubleBinding(new Callable<Double>() {
                        @Override
                        public Double call() {
                            return ResizingTextArea.this.getFont().getSize()+text.getBoundsInLocal().getHeight();
                        }
                    }, text.boundsInLocalProperty()));
                }
            }
        });
    }
}
